﻿
namespace MyFurion.Application
{
    /// <summary>
    /// 用户角色关联仓储
    /// </summary>
    public class UserRoleRepository:BaseRepository<UserRoleInfo>,ITransient
    {
        /// <summary>
        /// 授权用户角色
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="grantRoles">角色id</param>
        /// <returns></returns>
        public async Task GrantRole(long userId, List<long> grantRoles)
        {
            List<long> oldIds = await Context.Queryable<UserRoleInfo>().Where(p => p.UserId== userId).Select(p => p.Id).ToListAsync();
            //插入数据
            if (grantRoles.Any())
            {
                var roles = grantRoles.Select(u => new UserRoleInfo
                {
                    UserId = userId,
                    RoleId = u
                }).ToList();
                await Insert(roles);
            }
            //删除原有关联角色
            if (oldIds.Any())
            {
                await DeleteByWhere(p => oldIds.Contains(p.Id), true);
            }
        }
        /// <summary>
        /// 获取用户的角色Id集合
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<long>> GetUserRoleIdList(long userId)
        {
            return await Context.Queryable<UserRoleInfo>()
                .LeftJoin<RoleInfo>((u, r) => u.RoleId == r.Id)
                .Where((u, r) => r.Status == EnumStatus.Enabled && u.UserId == userId)
                .Select((u, r) => u.RoleId)
                .ToListAsync();
        }
    }
}
